package sw.service.impl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.easy.excel.ExcelContext;
import org.easy.excel.result.ExcelImportResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sw.dao.AssetDao;
import sw.dao.AssetTypeDao;
import sw.dao.ProjectDao;
import sw.dao.ThreatDao;
import sw.entity.Asset;
import sw.entity.AssetType;
import sw.entity.Project;
import sw.entity.Threat;
import sw.model.MAsset;
import sw.service.IThreatService;

@Service
public class ThreatServiceImpl implements IThreatService  {
	
	@Autowired
	private ProjectDao proDao;
	
	@Autowired
	private AssetDao assetDao;
	
	@Autowired
	private AssetTypeDao assetTypeDao;
	
	@Autowired
	private ThreatDao  threadDao;

	@Override
	public Map<String, List<MAsset>> showAllThreads(Integer projectId) {
		Project pro = proDao.findOne(projectId);
		List<Asset> assets =assetDao.findImportantAsset(projectId, pro.getImpStandard());
		if(null == assets) return null;
		Map<String, List<MAsset>> assetGroup = new HashMap<String, List<MAsset>>();
		 List<MAsset> temp;
		for(Asset asset :assets ){
			AssetType type = asset.getAssetType();
			String typeName = type.getName();
			if(assetGroup.containsKey(typeName)){
				temp = assetGroup.get(typeName);
			}else{
				temp = new ArrayList<MAsset>();
			}
			List<Threat> threaList = threadDao.findByAssetId(asset.getId());
			MAsset model = new MAsset(asset,threaList);
			temp.add(model);
			assetGroup.put(typeName, temp);
		}	
		return assetGroup;
	}
	
	@Override
	public Workbook exprotImpAsset(Integer projectId) throws Exception {
		int flag = 0;
		List<AssetType> types = (List<AssetType>) assetTypeDao.findAll();
		//创建excel上下文实例,它的构成需要配置文件的路径
		ExcelContext context = new ExcelContext("classpath:excelConfig/Threat.xml");
		Project pro = proDao.findOne(projectId);
		List<Asset> assets =assetDao.findImportantAsset(projectId, pro.getImpStandard());
		if(null == assets) return null;
		Map<String, List<Threat>> assetGroup = new HashMap<String, List<Threat>>();
		List<Threat> temp;
		for(Asset asset :assets ){
			AssetType type = asset.getAssetType();
			String typeName = type.getName();
			if(assetGroup.containsKey(typeName)){
				temp = assetGroup.get(typeName);
			}else{
				temp = new ArrayList<Threat>();
			}
			List<Threat> tList = threadDao.findByAssetId(asset.getId());
			if(null != tList && tList.size() != 0) flag =1;
			temp.addAll(tList);
			assetGroup.put(typeName, temp);
		}	
		Workbook workbook = new SXSSFWorkbook();
		if(flag == 1){
			for(String key :assetGroup.keySet()){
				List<Threat> threatList = assetGroup.get(key);
				if(null == threatList || threatList.size()==0) continue;
				workbook = context.createExcel(workbook,key,null,threatList);
			}
		}else{//导出重要资产
			workbook =	ExportImpAsset(projectId);
		}
		
		return workbook;
	}
	
	/**
	 * 没有导出过，则没有数据，需要导出重要资产
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	private Workbook ExportImpAsset(Integer projectId) throws Exception {
		List<AssetType> types = (List<AssetType>) assetTypeDao.findAll();
		//创建excel上下文实例,它的构成需要配置文件的路径
		ExcelContext context = new ExcelContext("classpath:excelConfig/ThreatInti.xml");
		Project pro = proDao.findOne(projectId);
		List<Asset> assets =assetDao.findImportantAsset(projectId,pro.getImpStandard());
		if(null == assets) return null;
		Map<String, List<Asset>> assetGroup = new HashMap<String, List<Asset>>();
		 List<Asset> temp;
		for(Asset asset :assets ){
			AssetType type = asset.getAssetType();
			String excelName = type.getImportExcel();
			if(assetGroup.containsKey(excelName)){
				temp = assetGroup.get(excelName);
			}else{
				temp = new ArrayList<Asset>();
			}
			temp.add(asset);
			assetGroup.put(excelName, temp);
		}	
		Workbook workbook = new SXSSFWorkbook();
		for(String key :assetGroup.keySet()){
			List<Asset> assetList = assetGroup.get(key);
			if(null == assetList) continue;
			workbook = context.createExcel(workbook,key,null,assetList);
		}
		return workbook;
	}

	@Override
	public void importExcel(String filePath, Integer projectId) throws Exception {
		//创建excel上下文实例,它的构成需要配置文件的路径
		ExcelContext context = new ExcelContext("classpath:excelConfig/Threat.xml");
		
		List<AssetType> types = (List<AssetType>) assetTypeDao.findAll();
		if(null == types || types.size() == 0 ){
			throw new RuntimeException("数据库配置错误！");
		}
		
		List<Threat> threatList = new ArrayList<Threat>();
		for(AssetType assetType :types){
			InputStream excelStream = new FileInputStream(filePath);
			ExcelImportResult result;
			try {
				System.out.println(assetType.getImportExcel());
				result = context.readExcel(assetType.getImportExcel(), 0, excelStream,true);
			} catch (Exception e) {
				continue;
			}
			if(result.hasErrors()){//导入文件出错
				throw new RuntimeException("数据导入出现错误"+result.getErrors());
			}
			List<Threat> threats = result.getListBean();
			if(null == threats || threats.size()==0) continue;
//			threatList.addAll(threats);
			for(Threat trt: threats){
				System.out.println(trt);
				threadDao.save(trt);
			}
		}
		
//		threadDao.save(threatList);
	}

}
